package com.idlestar.androiddocs.view.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.idlestar.androiddocs.R;
import com.idlestar.androiddocs.view.widget.ElasticListView;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class ElasticListViewActivity extends Activity {
    private ElasticListView mListView;
    private ArrayAdapter mAdapter;
    private EditText mItemNumText;
    private int mItemCount = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_elastic_list_view);
        mItemNumText = (EditText) findViewById(R.id.item_num);
        mListView = (ElasticListView) findViewById(R.id.list_view);
        mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mockData());
        initListView(mListView);
        mListView.setAdapter(mAdapter);
    }

    private void initListView(ListView listView) {
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(new ListView.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        ImageView headerImg = new ImageView(this);
        LinearLayout.LayoutParams imgLayoutParms = new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
        imgLayoutParms.weight = 2;
        headerImg.setLayoutParams(imgLayoutParms);
        headerImg.setScaleType(ImageView.ScaleType.CENTER_CROP);
        headerImg.setImageResource(R.mipmap.header_img);
        linearLayout.addView(headerImg);

        ImageView headerUnderLine = new ImageView(this);
        headerUnderLine.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, 6));
        headerUnderLine.setImageResource(R.drawable.horizontal_shadow);
        linearLayout.addView(headerUnderLine);
        listView.addHeaderView(linearLayout);

        listView.setHeaderDividersEnabled(false);
    }

    private String[] mockData() {
        String[] data = new String[mItemCount];
        for (int i = 0; i < mItemCount; i++) {
            data[i] = "我是第几? =" + i;
        }
        return data;
    }

    public void setListItemCount(View view) {
        String numStr = mItemNumText.getText().toString().trim();
        try {
            int newCount = Integer.valueOf(numStr);
            if (newCount == mItemCount) return;
            mItemCount = newCount;
        } catch (Exception e) {
            return;
        }

        mListView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, mockData()));
    }
}
